import { useDebounceFn } from "ahooks"
import { MutableRefObject } from "react"

export function delay(time: number = 1000) {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => resolve(), time)
    })
}

export function useInView(ref: MutableRefObject<any>, loadData: () => Promise<void>) {
    const { run, cancel, flush } = useDebounceFn(() => {
        const elem = ref.current
        if (elem == null) return
        const domRect = elem.getBoundingClientRect()
        if (domRect == null) return
        const { bottom } = domRect
        // 出现在视图内
        if (bottom <= document.body.clientHeight) {
            loadData();
        }
    }, {
        wait: 1000
    })

    return { run, cancel, flush }
}